package com.gitee.slowcreator.http.enhance.result;

import cn.hutool.core.lang.Singleton;
import cn.hutool.core.util.ArrayUtil;
import com.gitee.slowcreator.http.annotation.HttpResult;
import com.gitee.slowcreator.http.params.ScReturn;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 结果注入
 *
 * @author zxw
 * @date 2023/3/26 下午10:15
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ResultInject {

    public static <T> Object injectAndInvoke(
            Class<T> proxyInterface,
            ScReturn scReturn,
            Method method,
            Object[] args) throws InvocationTargetException, IllegalAccessException {

        if (ArrayUtil.isEmpty(args)) {
            return method.invoke(proxyInterface, args);
        }

        setAnnotationMarkValue(method.getParameterAnnotations(), args, scReturn);

        return method.invoke(Singleton.get(proxyInterface), args);
    }

    private static void setAnnotationMarkValue(Annotation[][] annotations,
                                               Object[] args,
                                               ScReturn scReturn) {

        for (int i = 0; i < annotations.length; i++) {
            Annotation[] paramAnn = annotations[i];
            for (Annotation annotation : paramAnn) {
                //这里判断当前注解是否为所需注解
                if (annotation.annotationType().equals(HttpResult.class)) {

                    args[i] = scReturn;
                    return;
                }
            }
        }
    }
}
